<template>
	<view class="kk-printer">
		<view class="kk-printer-btn" @tap="handlePrintTap" style="color:#F0F0F0;">
			{{isPrinting?printingText:defaultText}}
		</view>
		<view class="kk-shadow" :class="isShowSearch?'show':''" @tap="handleSearchClose">
			<view class="kk-modal" @tap.stop="doNothing">
				<view class="kk-search-device">
					<!-- <view class="kk-filter-wrap">
						<view class="filter-title">根据SRRI过滤设备</view>
						<slider @change="handleSRRIChange" max='-20' min='-100' value="-95" show-value/>
					</view> -->
					<view class="kk-filter-wrap">
						<view class="filter-title">根据蓝牙名过滤</view>
						<input type="text"  placeholder-class="kk-placeholder-class" placeholder="请输入蓝牙名字或设备ID搜索" v-model="filterName" />
					</view>
					<view class="kk-btn-wrap">
						<view class="kk-btn-item confirm-btn" @tap="startSearch" v-if="!isSearching">
							搜索设备
						</view>
						<view class="kk-btn-item confirm-btn" v-else>
							搜索中...
						</view>
						<view class="kk-btn-item" @tap="stopSearch">
							停止搜索
						</view>
					</view>
					<view class="kk-devices-wrap">
						<view class="empty-wrap" v-if="list.length <= 0">
							<view class="empty-icon"></view>
							<view class="empty-text">~ 无可搜索到的设备 ~</view>
						</view>
						<view class="" v-else>
							<!-- <view class="kk-devices-item" v-for="(item) in list" :data-title="item.deviceId" :data-name="item.name" :data-advertisData="item.advertisServiceUUIDs"
		 :key="item.deviceId"  @tap="handleConnectDevice()">
								<view class="name">
									<text>设备名称：</text>
									<text>{{item.name?item.name:'未命名'}}</text>
								</view>
								<view class="rssi">
									<text>信号强度：</text>
									<text>({{Math.max(0, item.RSSI + 100)}}%)</text>
								</view>
								<view class="deviceid">
									<text>设备ID：</text>
									<text>{{item.deviceId}}</text>
								</view>
								<view class="advmac" v-if="item.advMac">
									<text>advMac：</text>
									<text>{{item.advMac}}</text>
								</view>
							</view> -->
							<view v-for="(item) in list" :data-title="item.deviceId" :data-name="item.name" :data-advertisData="item.advertisServiceUUIDs"
							 :key="item.deviceId" @tap="bindViewTap">
								<view class="item">
									<view class="deviceId block">{{item.deviceId}}</view>
									<view class="name block">{{item.name}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>

	import {
		mapState
	} from 'vuex';
	export default {
		data(){
			return{
				//是否正在打印
				isPrinting:false,
				//是否正在搜索设备
				isSearching:false,
				//是否显示蓝牙列表
				isShowSearch:false,
				//按蓝牙名过滤
				filterName:'',
				//按信号过滤
				filterRSSI:-95,
				//设备列表
				devicesList:[],
				//连接的设备ID
				deviceId:'',
				//根据设备ID获取的服务
				
				writeId: '', 
				readId: '',
				list: [],
				services: [],
				serviceId: 0,
				writeCharacter: false,
				readCharacter: false,
				notifyCharacter: false,
				
				sendContent: "",
				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				returnResult: "",
				canvasWidth: 180,
				canvasHeight: 180,
				imageSrc: '../../static/img/abc_ic_star_black_16dp.png',
				buffSize: [],
				buffIndex: 0,
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isReceiptSend: false,
				isLabelSend: false
			}
		},
		props:{
			//按钮默认文字
			defaultText:{
				type:String,
				default:'完成并打印'
			},
			//按钮打印中的文字
			printingText:{
				type:String,
				default:'打印中'
			},
			bufferData:{
				type:String,
				require:true
			},
			roomcode:{
				type:String, 
				require:true
			},
			CustName:{
				type:String,
				require:true
			},
			roomid:{
				type:String,
				require:true
			},
			issave:{
				type:Boolean,
				require:true
			},
			
		},
		computed: mapState(['sysinfo', 'Bluetooth']),
		mounted() {
			
		},
		onLoad() {
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
			// uni.notifyBLECharacteristicValueChange({
			//   deviceId: BLEInformation.deviceId,
			//   serviceId: BLEInformation.notifyServiceId,
			//   characteristicId: BLEInformation.notifyCharaterId,
			//   state: true,
			//   success(res) {
			// 	uni.onBLECharacteristicValueChange(function(r) {
			// 	  console.log(`characteristic ${r.characteristicId} has changed, now is ${r}`)
			// 	})
			//   },
			//   fail: function(e) {
			// 	console.log(e)
			//   },
			//   complete: function(e) {
			// 	console.log(e)
			//   }
			// })
		},
		onReady(){
			let list = []
			let numList = []
			let j = 0
			for (let i = 20; i < 200; i += 10) {
			  list[j] = i;
			  j++
			}
			for (let i = 1; i < 10; i++) {
			  numList[i - 1] = i
			}
			this.buffSize = list;
			this.oneTimeData = list[0];
			this.printNum = numList;
			this.printerNum = numList[0];
		},
		onShow(){
			let that = this;
			let width;
			let height;
			uni.getImageInfo({
			  src: that.imageSrc,
			  success(res) {
				console.log(res.width)
				console.log(res.height)
				width = res.width
				height = res.height
				that.canvasWidth = res.width;
				that.canvasHeight = res.height;
			  }
			})
			const ctx = uni.createCanvasContext("edit_area_canvas", this);
			// if (app.globalData.platform == "android") {
			//   ctx.translate(width, height)
			//   ctx.rotate(180 * Math.PI / 180)
			// }
			ctx.drawImage(this.imageSrc, 0, 0, width, height);
			ctx.draw();
		},
		onUnload() {
			//停止搜索蓝牙设备
			if (this.isSearching) {
				uni.stopBluetoothDevicesDiscovery();
			};
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
		},
		beforeDestroy(){
			uni.stopBluetoothDevicesDiscovery();
		},
		
		computed: mapState(['sysinfo', 'Bluetooth']),
		methods:{
			doNothing(){
				return;
			},
			//错误码提示
			errorCodeTip(code) {
				if (code == 0) {
					//正常
				} else if (code == 10000) {
					uni.showToast({
						title: '未初始化蓝牙适配器',
						icon: 'none'
					})
				} else if (code == 10001) {
					uni.showToast({
						title: '当前蓝牙适配器不可用',
						icon: 'none'
					})
				} else if (code == 10002) {
					uni.showToast({
						title: '没有找到指定设备',
						icon: 'none'
					})
				} else if (code == 10003) {
					uni.showToast({
						title: '连接失败',
						icon: 'none'
					})
				} else if (code == 10004) {
					uni.showToast({
						title: '没有找到指定服务',
						icon: 'none'
					})
				} else if (code == 10005) {
					uni.showToast({
						title: '没有找到指定特征值',
						icon: 'none'
					})
				} else if (code == 10006) {
					uni.showToast({
						title: '当前连接已断开',
						icon: 'none'
					})
				} else if (code == 10007) {
					uni.showToast({
						title: '当前特征值不支持此操作',
						icon: 'none'
					})
				} else if (code == 10008) {
					uni.showToast({
						title: '其余所有系统上报的异常',
						icon: 'none'
					})
				} else if (code == 10009) {
					uni.showToast({
						title: 'Android 系统特有，系统版本低于 4.3 不支持 BLE',
						icon: 'none'
					})
				}
			},
			//点击打印按钮
			handlePrintTap(){
				let _this = this;
				let result = false;
				let isPrinting = this.isPrinting;

			if(!isPrinting){
				
				//状态已经是不在打印
				if(_this.issave){
				//获取已连接设备
				let aaa = _this.$store.state.Bluetooth.BLEInformation.deviceId;
				//aaa等于蓝牙id
				if(aaa){

					//有蓝牙id表示已经连接了蓝牙信息
					this.isPrinting = true;
					this.$emit('onPrint');
					
				}else{
					this.isShowSearch = true;
				}
				}else{
					console.log("4");
						let aaa = _this.$store.state.Bluetooth.BLEInformation.deviceId;
						//aaa等于蓝牙id
						if(aaa){
							//有蓝牙id表示已经连接了蓝牙信息
							this.isPrinting = true;
							this.$emit('onPrint');
							
						}else{
							this.isShowSearch = true;
						}
				}
			}else{
				//状态为非
				uni.showToast({
					title: "正在打印请稍等"
				});
				setTimeout(()=>{
					_this.isPrinting = false;
				},1000)
			}
				
			},
			//开始搜索蓝牙
			startSearch() {
				let that = this
				uni.openBluetoothAdapter({
					success(res) {
						uni.getBluetoothAdapterState({
							success(res2) {
								console.log('getBluetoothAdapterState:', res2)
								if (res2.available) {
									that.isSearching = true;
									if (res2.discovering) {
										uni.showToast({
											title: '正在搜索附近打印机设备',
											icon: "none"
										})
										return;
									}
			
									//获取蓝牙设备信息
									that.getBluetoothDevices()
			
									// that.checkPemission()
								} else {
									uni.showModal({
										title: '提示',
										content: '本机蓝牙不可用',
									})
								}
							}
						});
					},
					fail() {
						uni.showModal({
							title: '提示',
							content: '蓝牙初始化失败，请打开蓝牙',
						})
					}
				})
			},
			stopSearch() {
				uni.stopBluetoothDevicesDiscovery({
					success: (res) => {
						this.isSearching = false;
						console.log('stop:', res)
					},
					fail: (e) => {
						console.log('stop:', e)
						this.errorCodeTip(e.errCode);
					}
				})
			},
			//校验权限
			checkPemission() {
				let that = this
				let {
					BLEInformation
				} = that.Bluetooth;
				let platform = BLEInformation.platform;
				that.getBluetoothDevices();
			},
			//获取蓝牙设备信息
			getBluetoothDevices() {
				
				let that = this
				that.list = [];
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						// console.log(res)
						//蓝牙设备监听 uni.onBluetoothDeviceFound
						plus.bluetooth.onBluetoothDeviceFound((result) => {
							console.log('onBluetoothDeviceFound:', result)
							let arr = that.list;
							let devices = [];
							let list = result.devices;
							for (let i = 0; i < list.length; ++i) {
								if (list[i].name && list[i].name != "未知设备") {
									let arrNew = arr.filter((item) => {
										return item.deviceId == list[i].deviceId;
									});
									// console.log('arrNew:',arrNew.length)
									if (arrNew.length == 0) {
										devices.push(list[i]);
									}
								}
							}
			
							that.list = arr.concat(devices);
						});
						that.time = setTimeout(() => {
							// uni.getBluetoothDevices
							plus.bluetooth.getBluetoothDevices({
								success(res2) {
									let devices = [];
									let list = res2.devices;
									for (let i = 0; i < list.length; ++i) {
										if (list[i].name && list[i].name != "未知设备") {
											devices.push(list[i]);
										}
									}
			
									that.list = devices;
									console.log('getBluetoothDevices:',res2);
								},
							})
			
							clearTimeout(that.time);
						}, 3000);
					}
				});
			
			},
			//绑定蓝牙
			bindViewTap(e) {
				let that = this;
				let {
					title
				} = e.currentTarget.dataset;
				let {
					BLEInformation
				} = that.Bluetooth;
				this.stopSearch();
				that.serviceId = 0;
				that.writeCharacter = false;
				that.readCharacter = false;
				that.notifyCharacter = false;
				uni.showLoading({
					title: '正在连接',
				})
				console.log('deviceId:', title)
				// uni.createBLEConnection
				plus.bluetooth.createBLEConnection({
					deviceId: title,
					success(res) {
						console.log('createBLEConnection success:', res)
						BLEInformation.deviceId = title;
						that.$store.commit('BLEInformationSet', BLEInformation);
						uni.hideLoading();
						that.getSeviceId();
						setTimeout(()=>{
							that.isShowSearch = false;
							console.log('2');
						},1000);
						
					},
					fail(e) {
						that.errorCodeTip(e.errCode);
						uni.hideLoading()
					}
				})
			},
			//获取蓝牙设备所有服务(service)。
			getSeviceId() {
				let that = this;
				let {
					BLEInformation
				} = that.Bluetooth;
				console.log('BLEInformation.deviceId:',BLEInformation.deviceId)
				// uni.getBLEDeviceServices
				let t=setTimeout(()=>{
					plus.bluetooth.getBLEDeviceServices({
						deviceId: BLEInformation.deviceId,
						success(res) {
							console.log('getBLEDeviceServices success:',res)
							that.services = res.services;
							that.getCharacteristics()
						},
						fail: function(e) {
							that.errorCodeTip(e.code);	
							console.log('getBLEDeviceServices fail:',e)
						}
					})
					clearTimeout(t);
				},1500)
			},
			getCharacteristics() {
				var that = this
				let {
					services: list,
					serviceId: num,
					writeCharacter: write,
					readCharacter: read,
					notifyCharacter: notify
				} = that;
				let {
					BLEInformation
				} = that.Bluetooth;
				// uni.getBLEDeviceCharacteristics
				plus.bluetooth.getBLEDeviceCharacteristics({
					deviceId: BLEInformation.deviceId,
					serviceId: list[num].uuid,
					success(res) {
						// console.log(res)
						for (var i = 0; i < res.characteristics.length; ++i) {
							var properties = res.characteristics[i].properties
							var item = res.characteristics[i].uuid
							if (!notify) {
								if (properties.notify) {
									BLEInformation.notifyCharaterId = item;
									BLEInformation.notifyServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									notify = true
								}
							}
							if (!write) {
								if (properties.write) {
									BLEInformation.writeCharaterId = item;
									BLEInformation.writeServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									write = true
								}
							}
							if (!read) {
								if (properties.read) {
									BLEInformation.readCharaterId = item;
									BLEInformation.readServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									read = true
								}
							}
						}
						if (!write || !notify || !read) {
							num++
							that.writeCharacter = write;
							that.readCharacter = read;
							that.notifyCharacter = notify;
							that.serviceId = num;
							if (num == list.length) {
								uni.showModal({
									title: '提示',
									content: '找不到该读写的特征值',
								})
							} else {
								that.getCharacteristics()
							}
						} else {
							console.log("getCharacteristics:else")
							//that.openControl();
						}
					},
					fail: function(e) {
						console.log("getBLEDeviceCharacteristics fail：",e);
						that.errorCodeTip(e.errCode);	
					}
				})
			},
			openControl: function() {
				this.isShowSearch = true;
				// uni.navigateTo({
				// 	url: '/pages/sendCommand/sendCommand',
				// })
			},
			handleSearchClose(){
				this.isShowSearch = false;
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	.kk-printer{
		&-btn{
			width:100%;
			height:100%;
		}
		.kk-shadow{
			display: none;
			&.show{
				display: block;
				width:100vw;
				height:100vh;
				background: rgba(0,0,0,0.4);
				position: fixed;
				top: 0;
				left: 0;
				display: flex;
				justify-content: center;
				align-items: center;
				.kk-modal{
					width:680upx;
					height: 80%;
					padding:24upx;
					box-sizing: border-box;
					overflow-y: auto;
					border-radius: 20upx;
					background: #ffffff;
					display: flex;
					justify-content: center;
					align-items: center;
					.kk-search-device{
						width:100%;
						height: 100%;
						.kk-filter-wrap{
							width:100%;
							height: 160upx;
							display: flex;
							flex-direction: column;
							justify-content: flex-start;
							align-items: flex-start;
							.filter-title{
								line-height: 70upx;
								font-size: 30upx;
								color: #999999;
							}
							&>slider{
								width:90%;
								height: 90upx;
							}
							&>input{
								padding:0 20upx;
								box-sizing: border-box;
								border-radius: 10upx;
								height: 90upx;
								width:100%;
								border: 1upx solid #ebebeb;
							}
						}
						.kk-btn-wrap{
							width:100%;
							height: 140upx;
							display: flex;
							justify-content: space-between;
							align-items: center;
							&>view{
								flex:1 1 auto;
								height: 100upx;
								line-height: 100upx;
								border-radius: 16upx;
								text-align: center;
								color:#ffffff;
								&.confirm-btn{
									background: #007AFF;
									margin-right:30upx;
								}
								&:nth-last-child(1){
									background: #DD524D;
								}
							}
						}
						.kk-devices-wrap{
							height: calc(100% - 460upx);
							overflow-y:auto;
							padding:10upx 20upx;
							box-sizing: border-box;
							border: 1upx solid #ebebeb;
							box-sizing: border-box;
							border-radius: 20upx;
							.empty-wrap{
								width:100%;
								height: 100%;
								display: flex;
								flex-direction: column;
								justify-content: center;
								align-items: center;
								.empty-icon{
									width:268upx;
									height: 240upx;
									// background: url('./empty-icon.png') no-repeat;
									background-size:100% 100%;
									margin-bottom: 26upx;
								}
								.empty-text{
									width: 100%;
									line-height: 50upx;
									font-size: 30upx;
									text-align: center;
									color: #999999;
								}
							}
							.kk-devices-item{
								width:100%;
								border-bottom: 1upx solid #ebebeb;
								padding:10upx 0;
								box-sizing: border-box;
								&:nth-last-child(1){
									border-bottom: none;
								}
								&>view{
									width:100%;
									font-size: 30upx;
								}
							}
						}
					}
				}
			}
			
		}
	}
	.kk-placeholder-class{
		font-size: 30upx;
		color:#999999;
	}
	.kk-printer-btn{
		background-color: #e43d33;
		border: 1px solid #f8f8f8;
		border-radius: 8rpx;
		font-size: 30rpx;
		line-height: 62rpx;
		padding: 0 6rpx ;
		text-indent: 10rpx;
	}
	.item{
		margin-top: 20rpx;
	}
</style>
